//
//  BuyOrSellDetailViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/24.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import ZendeskSDK
class BuyOrSellDetailViewController: AccountBaseViewController {

    @IBOutlet weak var amountInput: InputView!
    @IBOutlet weak var moneyInput: InputView!
    ///头部
    @IBOutlet weak var inputContainerView: UIView!
    @IBOutlet weak var varietyIcon: UIImageView!
    @IBOutlet weak var wantToBuy: UILabel!
    ///交易范围提示
    @IBOutlet weak var exchangeLimit: UILabel!
    
    ///交易用户信息
    @IBOutlet weak var userIcon: UIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var userPayType: UIButton!
    @IBOutlet weak var userLimit: UILabel!
    ///交易次数
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var exchangeTime: UILabel!
    @IBOutlet weak var exchangeTimeTitle: UILabel!
    @IBOutlet weak var trustAccount: UILabel!
    @IBOutlet weak var trustAccountTitle: UILabel!
    @IBOutlet weak var favorableRate: UILabel!
    @IBOutlet weak var favorableRateTitle: UILabel!
//    @IBOutlet weak var history: UILabel!
//    @IBOutlet weak var historyTitle: UILabel!
    @IBOutlet weak var leaveMessage: UILabel!
    
    ///交易提示
    @IBOutlet weak var tip: UILabel!
    @IBOutlet weak var tipContent: UILabel!
    
    @IBOutlet weak var sureBtn: UIButton!
    
    @IBOutlet weak var bottomFloatView: UIView!
    
    @IBOutlet weak var buyOrSellBtn: UIButton!
    
    @IBOutlet weak var contactBtn: UIButton!
    
    var type: BuyOrSellType = .buy
    
    var coinModel: TradeCoinModel?
    
//    var model: AdvertisingListModel?
    
    var adId: Int = 0
    
    var dyPrice: Double = 0
    
    var timer: Timer?

    lazy var viewModel: AdvertisingDetailViewModel =  {
        let vm = AdvertisingDetailViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            
            if isSuccess {
                if state == ResponseState.trade_ad_detail {
                    self?.reload()
                }else if state == ResponseState.trade_order_create {
                    self?.goChat(type: 1)
                }else if state == ResponseState.trade_ad_chat {
                    self?.goChat(type: 0)
                }
            }else {
                if let msg = errorMsg {
                    CYMBShow.showMessage(msg)
                }else {
                    CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                }
            }
        }
        return vm
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    func initUI() {
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: kText("帮助"), style: .plain, target: self, action: #selector(help))
        //
        
        userIcon.layer.cornerRadius = 18
        userIcon.layer.masksToBounds = true
        
        self.moneyInput.delegate = self
        self.amountInput.delegate = self
        self.moneyInput.style = .title
        self.moneyInput.input.keyboardType = .decimalPad
        self.amountInput.style = .title
        self.amountInput.input.keyboardType = .decimalPad
        
        let shapeLayer = CAShapeLayer()
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 5, y: 0))
        path.addLine(to: CGPoint(x: self.inputContainerView.width - 5, y: 0))
        path.addQuadCurve(to: CGPoint(x: self.inputContainerView.width, y: 5), controlPoint: CGPoint(x: self.inputContainerView.width, y: 0))
        path.addLine(to: CGPoint(x: self.inputContainerView.width , y: self.inputContainerView.height - 5))

        path.addQuadCurve(to: CGPoint(x: self.inputContainerView.width - 5, y: self.inputContainerView.height), controlPoint: CGPoint(x: self.inputContainerView.width, y: self.inputContainerView.height))
        path.addLine(to: CGPoint(x: 5 , y: self.inputContainerView.height))
        
        path.addQuadCurve(to: CGPoint(x: 0, y: self.inputContainerView.height - 5), controlPoint: CGPoint(x: 0, y: self.inputContainerView.height))
        
        path.addLine(to: CGPoint(x: 0 , y: 5))
   
        path.addQuadCurve(to: CGPoint(x: 5, y: 0), controlPoint: CGPoint(x: 0, y: 0))
        
        shapeLayer.fillColor = self.view.backgroundColor?.cgColor
        shapeLayer.path = path.cgPath
        
        self.inputContainerView.layer.insertSublayer(shapeLayer, at: 0)
        self.inputContainerView.layer.shadowOpacity = 0.8
        self.inputContainerView.layer.shadowOffset = CGSize(width: 0, height: 0)
        self.inputContainerView.layer.shadowRadius = 2
        self.inputContainerView.layer.shadow = ThemeManager.ThemeColorKeys.separator
        
        self.exchangeLimit.isHidden = true
        self.contactBtn.layer.cornerRadius = 3
        self.contactBtn.layer.border = ThemeManager.ThemeColorKeys.text2
        self.contactBtn.layer.borderWidth = 1
        self.contactBtn.layer.masksToBounds = true
        self.buyOrSellBtn.layer.cornerRadius = 3
        self.buyOrSellBtn.layer.masksToBounds = true
        
        
        self.tipContent.text = kText("1、交易前请详细了解对方的交易信息。\n2、请通过平台进行沟通约定，并保存好相关聊天记录。\n3、如遇到交易纠纷，请通过平台“帮助”解决问题。")
        
    }
    
    func initData() {
        viewModel.getAdvertisingDetail(adId: self.adId)
    }
    
    func reload() {
        guard let model = viewModel.dataModel else { return }
        coinModel = AppContext.default.loadTradeCoinPrecision(coinCode: self.viewModel.dataModel?.moneyType ?? "")
        if model.type == 1 {
            self.title = kText("购买1") + (model.moneyType ?? "")
            self.wantToBuy.text = kText("你要购买多少？")
            self.moneyInput.placeholder = kText("请输入购买金额")
            self.amountInput.placeholder = kText("请输入购买数量")
            buyOrSellBtn.setTitle(kText("立即购买"), for: .normal)
        }else {
            self.title = kText("出售1") + (model.moneyType ?? "")
            self.wantToBuy.text = kText("你要出售多少？")
            self.moneyInput.placeholder = kText("请输入出售金额")
            self.amountInput.placeholder = kText("请输入出售数量")
            buyOrSellBtn.setTitle(kText("立即出售"), for: .normal)
        }
        
        self.moneyInput.title = model.currency
        self.amountInput.title = model.moneyType
        if let p = model.portrait, let url = URL(string: p) {
            self.userIcon.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "login_icon"))
        }else {
            self.userIcon.image = #imageLiteral(resourceName: "login_icon")
        }
        self.userName.text = model.userName
        if model.paymentMethod == 2 {
            self.userPayType.setBackgroundImage(#imageLiteral(resourceName: "unionPay"), for: .normal)
        }else {
            self.userPayType.setBackgroundImage(#imageLiteral(resourceName: "aliPay"), for: .normal)
        }
        
        self.exchangeTime.text = "\(model.dealCount ?? 0)"
        self.trustAccount.text = "\(model.trustNum ?? 0)"
        self.favorableRate.text = model.highOpinionRatio
//        self.history.text = String(format: "%0.2lf", model.historyDealAmount ?? 0)
        
        let lowest = model.limitLowerMoney ?? 0
        let high = model.limitUpperMoney ?? 0
        self.userLimit.text = String(format: "%@ %0.2lf~%0.2lf %@", kText("交易限额"),lowest,high,model.currency ?? "")
        self.exchangeLimit.text = self.userLimit.text
        self.leaveMessage.text = kText("广告留言") + ":" + (model.message ?? "--")
        self.reloadTick()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.timer = Timer.scheduledTimer(timeInterval: 60 * 5, target: self, selector: #selector(reloadTick), userInfo: nil, repeats: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.timer?.invalidate()
        self.timer = nil
    }
    
    @objc func reloadTick() {
        dPrint("reloadTick")
        guard let model = viewModel.dataModel else { return }
        let currency = model.currency ?? ""
        if let exTick = AppContext.default.exTickData {
            let datas = exTick.filter { (data) -> Bool in
                return data["money"] as? String == currency
            }
            if let data = datas.first,let symbols = data["symbols"] as? [String:Double]  {
                if var exPrice = symbols[(model.moneyType ?? "")] {
                    exPrice = exPrice + exPrice * (model.premium ?? 0) / 100
                    dyPrice = exPrice
                }
            }
        }
        self.price.text = String(format: "%0.2lf %@", dyPrice,currency)
        if let text = self.amountInput.input.text, text.count > 0 {
            self.inputViewTextDidChange(inputView: self.amountInput)
        }
    }
    
    // MARK: - event
    @objc func help() {
       dPrint("帮助")
        let viewController = ZDKHelpCenterUi.buildHelpCenterOverview()
        let nav = UINavigationController(rootViewController: viewController)
        self.present(nav, animated: true, completion: nil)
    }
    
    ///点击购买
    @IBAction func sure(_ sender: Any) {
        dPrint("确认")
        
    }
    ///0 广告会话 1 订单会话
    func goChat(type: Int) {
        let vc = ExchangeChatViewController()
        if type == 0 {
            vc.adId = viewModel.adId
            vc.adChatId = viewModel.adChatId
        }else {
            vc.orderId = viewModel.orderId
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }

    @IBAction func contact(_ sender: Any) {
        dPrint("联系")
        self.viewModel.createAdChat(adId: self.adId)
    }
    
    @IBAction func sell(_ sender: Any) {
        let money = Double(self.moneyInput.input.text!) ?? 0
        if money <= Double(0) {
            CYMBShow.showMessage(kText("交易金额必须大于零"))
            return
        }
        
        let amount = Double(self.amountInput.input.text!) ?? 0
        if amount <= Double(0) {
            CYMBShow.showMessage(kText("交易数量必须大于零"))
            return
        }
        
        
        dPrint("出售")
        guard let model = viewModel.dataModel else {
            CYMBShow.showMessage(kText("未获取到相关数据"))
            return
        }
        
        if let buyMoney = Double(self.moneyInput.input.text ?? ""),let lower = model.limitLowerMoney,let upper = model.limitUpperMoney {
            if buyMoney >= lower && buyMoney <= upper {
                let buyPop = BuyOrSellSurePopView.loadFromNib() as!BuyOrSellSurePopView
                let moneyType = model.moneyType ?? ""
                let currency = model.currency ?? ""
                buyPop.price.text = String(format: "%0.2lf ", dyPrice) + currency
                buyPop.account.text = (self.amountInput.input.text ?? "") + " " +  moneyType
                buyPop.money.text = (self.moneyInput.input.text ?? "") + " " + currency
                buyPop.tip.text = String(format: kText("提醒：请确认价格再下单，下单后此交易的%@将托管锁定，请放心购买。"), model.moneyType ?? "")
                buyPop.sure = {
                    let dy = String(format: "%0.2f", self.dyPrice)
                    self.viewModel.createTradeOrder(unitPrice: Double(dy)!, amount: Double(self.moneyInput.input.text!)!, quantity: Double(self.amountInput.input.text!)!, adId: self.adId)
                }
                buyPop.show()
                return
            }
        }
        CYMBShow.showMessage(kText("请输入限价范围内的价格"))
    }
    
}

extension BuyOrSellDetailViewController: InputViewDelegate {
    func inputViewTextDidChange(inputView: InputView) {
//        dPrint(inputView.input.text!)
        self.exchangeLimit.isHidden = !inputView.input.hasText
        var text = inputView.input.text!
        if text == "." {
            text = ""
        }else {
            let c1 = text.first
            if c1 == "0" {
                if text.count >= 2 {
                    let index2 = text.index(text.startIndex, offsetBy: 1)
                    let c2 = text[index2]
                    if c2 != "." {
                        text.removeFirst()
                    }
                }
            }
        }
        let cs = text.filter { (c) -> Bool in
            return c == "."
        }
        if cs.count > 1 {
            text = deleteDot(text: text)
        }
        
        if text.contains("."), text.last != ".",let num = Double(text) {
            if inputView == self.moneyInput {
                inputView.input.text = CYCalculate.cy_intercept(number: num, digit: 2)
            }else {
                inputView.input.text = CYCalculate.cy_intercept(number: num, digit: 8)
            }
        }
        text = inputView.input.text!
//        inputView.input.text = text
        
        if inputView == self.moneyInput {
            if let money = Double(text) {
                if dyPrice <= 0 {
                   self.amountInput.input.text = "0"
                }else {
                    self.amountInput.input.text = CYCalculate.cy_intercept(number: money / dyPrice, digit: coinModel?.coinPrecision ?? 8)
                }
            }else {
                self.amountInput.input.text = ""
                if text.count > 0 {
                    CYMBShow.showMessage(kText("请输入正确的数据格式"))
                }
            }
        }else if inputView == self.amountInput {
            if let amount = Double(text) {
                self.moneyInput.input.text = String(format: "%0.2lf", amount * dyPrice)
            }else {
                self.moneyInput.input.text = ""
                if text.count > 0 {
                    CYMBShow.showMessage(kText("请输入正确的数据格式"))
                }
            }
        }
         dPrint(inputView.input.text!)
    }
    
    func deleteDot(text: String) -> String {
        var text = text
        if let range = text.range(of: ".", options: String.CompareOptions.backwards, range: nil, locale: nil)  {
            text.removeSubrange(range.lowerBound..<text.endIndex)
            let _ = deleteDot(text: text)
        }
        return text
    }
}
